// Package handler
// @Author: zhangdi
// @File: HandlerSendBefore
// @Version: 1.0.0
// @Date: 2023/7/3 18:24
package handler

import (
	"fmt"
	"ideatools/application/constant"
	"ideatools/application/constant/enums"
	"ideatools/application/core/toast"
	"ideatools/application/db/columns"
	"ideatools/application/db/dbdto"
	"ideatools/application/db/dbservice"
	"ideatools/application/db/repository"
	"ideatools/application/db/sqllite"
	"ideatools/application/pkgs/clips"
	"ideatools/application/pkgs/mylog"
	"ideatools/application/pkgs/utils"
	"ideatools/application/pkgs/where"
	"ideatools/application/service"
)

func (s *HandlerMessageService) GetToolInfoByChatDialogId(dialogId uint) *dbdto.UserToolInfo {
	dialogInfo := dbservice.ChatDialog().GetDialogInfo(dialogId)
	if dialogInfo == nil {
		return nil
	}

	return s.GetToolInfo(dialogInfo.ToolId)
}

func (s *HandlerMessageService) GetToolInfo(ToolId uint) *dbdto.UserToolInfo {
	ToolInfo := s.DbToolService.FindOneById(ToolId)
	ToolInfoDto := &dbdto.UserToolInfo{}
	utils.DtoToEntity(ToolInfo, ToolInfoDto)
	if ToolInfo == nil {
		mylog.Error("HandlerMessageService.Send() : 查询UserTool 的信息为nil")
		return nil
	}
	return ToolInfoDto
}

func (s *HandlerMessageService) GetClipTexts(NeedCount int) []string {
	if NeedCount <= 0 {
		return make([]string, 0)
	}

	clipService := repository.NewClipboardRepository(sqllite.GetDb())
	listClip, _ := clipService.FindListExtra(where.Format(where.Opt(columns.ClipboardId, ">", 0)), &where.Extra{
		OrderByColumn: "id",
		OrderByDesc:   true,
		Limit:         int(NeedCount),
	})

	if len(listClip) < int(NeedCount) {
		mylog.Error(fmt.Sprintf("剪切板数量不足%v个", NeedCount))
		return nil
	}
	clipTexts := []string{}
	for _, item := range listClip {
		clipTexts = append(clipTexts, item.Content)
	}

	return clipTexts
}

func CanSend() bool {
	GptConf := GetGptConfig()
	if dbservice.Conf().Get(constant.ConfigKeyAiMode) == enums.AiModeOpenKey {
		if GptConf.OpenAiKey == "" {
			toast.FrontError("openai key 未填写，请先到系统设置-AI设置中填写", 4000)
			return false
		}
		if GptConf.ProxyType == enums.ProxyTypeLocal && GptConf.ProxyLocalUrl == "" {
			toast.FrontError("本地代理地址还没填写，，请先到系统设置-AI设置中填写", 4000)
			return false
		}
		if GptConf.ProxyType == enums.ProxyTypeUserServe && GptConf.ProxyServerUrl == "" {
			toast.FrontError("远程代理地址还没填写，请先到系统设置-AI设置中填写", 4000)
			return false
		}

		if GptConf.ProxyType == enums.ProxyTypeZhiJianServe && GptConf.ProxyServerUrl == "" {
			toast.FrontError("您选择的代理模式仅限购买了云备份服务的用户使用，请先购买云备份服务", 4000)
			return false
		}
	} else {
		if !service.IsLogin() {
			toast.FrontError("i豆模式下需要先登录，请点击左下角进行登录", 4000)
			return false
		}
	}
	return true
}

func copySendContent(sendContent string) {
	err := clips.SetText(sendContent)
	if err != nil {
		toast.SysInfo("复制异常", err.Error())
	} else {
		toast.SysInfo("prompt内容已复制", "prompt内容已经组装好并复制到剪切板")
	}
}

// GetChatDialogId 获取对话id
func GetChatDialogId(toolId, dialogId uint, clipTexts []string) uint {
	if dialogId <= 0 {
		res := dbservice.ChatDialog().CreateChatDialog(toolId, clipTexts)
		if res.Code == 0 {
			mylog.Error("创建对话失败：GetChatDialogId()" + res.Msg)
			return 0
		} else {
			return res.Data.(uint)
		}
	}
	return dialogId
}

func (s *HandlerMessageService) SendContentAddToDb(dialogId uint, userSendContent string, isNotify bool, clipTexts []string) {
	if !CanSend() {
		return
	}
	userContent, err := dbservice.ChatDialog().AddChatContent(dialogId, userSendContent, enums.GptRoleUser)
	if err != nil {
		toast.SysInfo("user消息入库失败", err.Error())
		return
	}

	AIContent, err := dbservice.ChatDialog().AddChatContent(dialogId, "", enums.GptRoleAI)
	if err != nil {
		toast.SysInfo("ai消息入库失败", err.Error())
		return
	}

	if isNotify {
		NotifyFrontMessageContent(userContent, clipTexts) //用户消息
		NotifyFrontMessageContent(AIContent, nil)

	}
	s.CurrChatUserContent = userContent
	s.CurrChatAiContent = AIContent
	//return userContent, AIContent
}
